package com.closer.service.api;

import com.closer.service.biz.user.dto.*;
import com.closer.service.biz.user.dto.vo.LoginUserVO;
import com.closer.service.biz.user.dto.vo.UserVO;
import com.closer.service.biz.user.entity.User;
import com.closer.service.support.annotation.AuthCheck;
import com.closer.service.support.common.BaseResponse;
import com.closer.service.support.common.DeleteRequest;
import com.closer.service.support.common.ResultUtils;
import com.closer.service.support.constant.UserConstant;
import com.closer.service.support.exception.BusinessException;
import com.closer.service.support.exception.ErrorCode;
import com.closer.service.support.exception.ThrowUtils;
import com.mybatisflex.core.paginate.Page;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.*;
import com.closer.service.biz.user.service.UserService;

import static com.closer.service.support.constant.UserConstant.USER_LOGIN_STATE;

/**
 * 用户 控制层。
 *
 * @author closer
 */
@RestController
@RequestMapping("/user")
public class UserController {

    private final UserService userService;

    public UserController(UserService userService) {
        this.userService = userService;
    }

    @PostMapping("register")
    public BaseResponse<Long> userRegister(@RequestBody UserRegisterRequest params) {
        var result = userService.userRegister(params);
        return ResultUtils.success(result);
    }

    @PostMapping("/login")
    public BaseResponse<LoginUserVO> userLogin(@RequestBody UserLoginRequest params, HttpServletRequest request) {
        var loginUserVO = userService.userLogin(params);
        // 3. 记录用户的登录态
        request.getSession().setAttribute(USER_LOGIN_STATE,loginUserVO);
        return ResultUtils.success(loginUserVO);
    }

    @GetMapping("/get/login")
    public BaseResponse<LoginUserVO> getLoginUser(HttpServletRequest request) {
        var userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
        var loginUser = (LoginUserVO) userObj;
        if(loginUser == null || loginUser.getId() == null){
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR,"未登陆");
        }
        return ResultUtils.success(loginUser);
    }

    @PostMapping("/logout")
    public BaseResponse<Boolean> userLogout(HttpServletRequest request) {
        ThrowUtils.throwIf(request == null, ErrorCode.PARAMS_ERROR);
        var userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
        if(userObj == null ){
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR,"未登陆");
        }
        request.getSession().removeAttribute(USER_LOGIN_STATE);
        return ResultUtils.success(true);
    }

    /**
     * 创建用户
     */
    @PostMapping("/add")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Long> addUser(@RequestBody UserAddRequest params) {
        var result = userService.add(params);
        return ResultUtils.success(result);
    }

    /**
     * 根据 id 获取用户（仅管理员）
     */
    @GetMapping("/get")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<User> getUserById(long id) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        var user = userService.getById(id);
        ThrowUtils.throwIf(user == null, ErrorCode.NOT_FOUND_ERROR);
        return ResultUtils.success(user);
    }

    /**
     * 根据 id 获取包装类
     */
    @GetMapping("/get/vo")
    public BaseResponse<UserVO> getUserVOById(long id) {
        var response = getUserById(id);
        var user = response.getData();
        return ResultUtils.success(userService.getUserVO(user));
    }

    /**
     * 删除用户
     */
    @PostMapping("/delete")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> deleteUser(@RequestBody DeleteRequest deleteRequest) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        var b = userService.removeById(deleteRequest.getId());
        return ResultUtils.success(b);
    }

    /**
     * 更新用户
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateUser(@RequestBody UserUpdateRequest params) {
        var result = userService.updateUser(params);
        return ResultUtils.success(result);
    }


    @PostMapping("/list/page/vo")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<UserVO>> listUserVOByPage(@RequestBody UserQueryRequest params) {
        var userVOPage = userService.listUserVOByPage(params);
        return ResultUtils.success(userVOPage);
    }

}
